#include "ReaderThread.h"
#include "WatermarkManager.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <log/log.h>
#include <iostream>
#include <stdio.h>
#include <cstring>

namespace android {

ReaderThread::ReaderThread(WatermarkManager* manager, BufferQueue<WMarkBuffer>* queue)
{
    mManager = manager;
    mBufferQueue = queue;

    mTestCount = 0;
}

ReaderThread::~ReaderThread() {

}

int ReaderThread::recvMsg(WMarkBuffer* buf) {
    // testing code , should be removed 
    mTestCount ++;
    if (mTestCount > 1024)
        mTestCount = 0;

    char *data;
    // testing code end

    data = (char*)(buf -> Data());
    std::sprintf(data, "%s speed: %04d (km/h)", "2021-10-25", mTestCount);
    buf -> setSize(std::strlen(data));
    ALOGE("%s, buf=%s buf size=%d\n", __func__, (char*)buf->Data(), buf->getSize());

    //TODO read data to buf->Data()
    
    return buf -> getSize();

}

void ReaderThread::start() {
    this -> run("ReaderThread", PRIORITY_HIGHEST);
}

void ReaderThread::stop() {
    requestExitAndWait();
}

bool ReaderThread::threadLoop() {
    WMarkBuffer* buf = mBufferQueue -> dequeueProducerBuffer();

    // from hidl interface get speed/date
    // getSpeedDate();

    recvMsg(buf);

    mBufferQueue -> enqueueConsumerBuffer(buf);
    mManager -> notifyDataReady();
    // should remove sleep
    // sleep(1);

    return true;
}

} //namespace
